<?php

declare(strict_types=1);

namespace app\common\model;

use think\facade\Event;
use app\common\controller\Config;
use addons\Target\facade\Target;
use addons\Pay\facade\Pay;

class Merchant extends Base
{
    protected $name = 'merchant';


    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile,parent_id');
    }


    public static function getTakeOverTableList($that, $param, $filed = '*', $count = 0)
    {
        try {
            foreach ($that as &$v) {
                $v->saleroom = Order::where(['merchant_id' => $v->id, 'pay_state' => 2, 'shop_type' => 2])->sum('real_amount');
            }
            return ['code' => 0, 'data' => $that, 'count' => $count];
        } catch (\Exception $e) {
            return [];
        }
    }
    public function getStatusAttr($value)
    {
        switch ($value) {
            case 1:
                return '待审核';
            case 2:
                return '已通过';
            default:
                return '已拒绝';
        }
    }


    public static function add($param, $user): array
    {
        $sys = Config::lists();
        try {
            $info = parent::where(['uid' => $user->id])->find();
            $param['money'] = $sys['enter_money'];
            $account = $param['pay_way'];
            unset($param['agree']);
            unset($param['pay_way']);
            if (!empty($info)) {
                if ($info->getData('status') == 3) {
                    $param['status'] = 1;
                    parent::where(['id' => $info->id])->update($param);
                    return self::deductMoney($sys['enter_money'], $user, $account);
                } else if ($info->getData('status') == 1) {
                    return ['code' => 1, 'msg' => '您已提交申请，请耐心等待审核'];
                } else {
                    return ['code' => 1, 'msg' => '您已是商家，无需重复申请'];
                }
            } else {
                //申请已提交，请耐心等待审核
                $param['uid'] = $user->id;
                parent::create($param);
                return self::deductMoney($sys['enter_money'], $user, $account);
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 入驻费用扣款
     */
    public static function deductMoney($money, $user, $account)
    {
        try {

            switch ($account) {
                case 'bonus':
                    if ($user->assets->bonus < $money) {
                        return ['code' => -1, 'msg' => '金币不足'];
                    }
                    Target::Account()->basics($user->id, 'bonus', $money, '商家申请入驻费用', '-')
                        ->createNormal();
                    return ['code' => 1, 'msg' => '申请已提交，请耐心等待审核'];
                    break;
                case 'wechat':
                    $info = MerchantOrder::create([
                        'sn'              => 'M' . date('YmdHis') . $user->id . rand(100000, 999999),
                        'uid'             => $user->id,
                        'money'           => $money,
                    ]);
                    $return_url = 'http://' . $_SERVER['HTTP_HOST'] . '/index/user/index.html';
                    $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/index/callback/wechatMerchantCallback';
                    $options = Pay::setDriver('WeChat')
                        ->setReturnUrl($return_url)
                        ->basic('商家入驻', $info->sn, $info->money, $notifyUrl)
                        ->create('MWEB');
                    return ['code' => 1, 'msg' => '支付中', 'url' => $options];
                    break;
                default:
                    return ['code' => -1, 'msg' => '支付方式错误'];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 审核
     */
    public static function _save($param, $logs)
    {

        parent::startTrans();
        try {
            if (!isset($param['status'])) return ['code' => -1, 'msg' => '请选择审核类型'];

            $info = parent::find($param['id']);
            if (empty($info)) return ['code' => -1, 'msg' => '审核失败'];
            if ($info->getData('status') != 1) {
                return ['code' => -1, 'msg' => '此笔记录已审核，请勿重复审核！'];
            }
            if ($param['status'] == 2) {
                $msg = '通过商家入驻申请，ID【' . $param['id'] . '】';
                User::where(['id' => $info->uid])->update(['is_merchant' => 1]);
                self::tpMoney($info->money, $info->user);
            } else {
                $msg = '驳回商家入驻申请,ID【' . $param['id'] . '】';
                Target::Account()->basics($info->uid, 'bonus', $info['money'], '商家入驻费用退还', '+')
                    ->createNormal();
            }

            $info->status = $param['status'];
            if ($param['status'] != 2) {
                $info->reject_msg = $param['reject_msg'];
            }
            $info->admin_id = $logs['admin']->id;
            $info->admin_name = $logs['admin']->admin_name;
            $info->confirm_time = time();
            $info->save();
            Logs::adds($msg, $logs['admin']->id, $logs['admin']->admin_name);
            parent::commit();
            return ['code' => 1, 'msg' => '已审核'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 批量审核
     */
    public static function batch($ids, $admin)
    {
        parent::startTrans();
        try {
            $infos = parent::where('status', 1)->whereIn('id', $ids)->select();
            if ($infos->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到待审核的数据，请检查！'];
            }
            $newIds = [];
            $newUids = [];
            foreach ($infos as $v) {
                $newIds[] = $v->id;
                $newUids[] = $v->uid;
            }
            User::whereIn('id', $newUids)->update(['is_merchant' => 1]);
            parent::update(['status' => 2, 'admin_id' => $admin->id, 'admin_name' => $admin->admin_name], ['id' => $newIds]);
            parent::commit();
            $msg = '批量通过商家入驻申请,标识ID【' . implode(',', $ids) . '】';
            Logs::adds($msg, $admin['id'], $admin['admin_name']);
            return ['code' => 1, 'msg' => '已批量审核'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 商家入驻推荐奖
     */
    public static function tpMoney($money, $user)
    {

        $sys = Config::lists();
        try {
            $tp_money = 0;
            /**推荐奖 */
            if ($user->parent_id != 0) {
                $tp_money = round($money * $sys['tp_3'], 2);
                Target::Account()->basics($user->parent_id, 'bonus', $tp_money, '商家入驻推荐奖', '+')
                    ->createBonus($user->id, 7);
            }
            if ($tp_money > 0) {
                //统计收入，则需使用
                Event::trigger('Statistics', ['key' => 'expend', 'value' => ($tp_money)]);
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 回调
     */ 
     public static function operations($info, $user, $account): array
     {
        $sys = Config::lists();
        parent::startTrans();
        try {
            $info->pay_way = $account;
            $info->pay_state = 2;
            $info->pay_time = time();
            $info->save();
            //统计收入，则需使用
            parent::commit();
            return ['code' => 1, 'msg' => '申请已提交，请耐心等待审核', 'url' => url('user/index')->build()];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
